<script setup>
import { ref } from 'vue'
import { UserFilled, Lock } from '@element-plus/icons-vue'
import Vcode from 'vue3-puzzle-vcode'
import { rules } from '@/utils/Login/formRules'

import { useRouter } from 'vue-router'
import { getKey, removeKey, setKey } from '@/utils/common/localStorage'
import { loginApi, registerApi } from '@/api/login'
import { useUserStore } from '@/stores/user'
import { showMessage } from '@/utils/common/showMessage'
const userStore=useUserStore()
const router = useRouter()
const userInfo = getKey('userinfo')

const form = ref({
  account: userInfo ? userInfo.account : '',
  password: userInfo ? userInfo.password : ''
})
const registerForm = ref({
  account: '',
  password: '',
  repassword: ''
})
const loginFormRef = ref(null)
const registerFormRef = ref(null)
// 拼图验证函数
const isShow = ref(false)

// 是否选择记住密码
const formSaveVal = ref(false)

const activeName = ref('login')

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value != registerForm.value.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}
const registerRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 8, message: '长度至少4位,最多8位', trigger: ['change', 'blur'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码必须大于6个字符', trigger: ['change', 'blur'] }
  ],
  repassword: [
    { validator: validatePass, trigger: 'change' },
    { required: true, message: '请确认密码', trigger: 'blur' }
  ]
}
// 表单重置
function resetForm() {
  loginFormRef.value.resetFields()
  form.value.account = ''
  form.value.password = ' '
}

// tab切换
function handleTabClick(tab, event) {
  console.log(tab)
}
// 登录表单提交
function onLogin(type) {
  switch (type) {
    case 'register':
    registerClick()
      break
    case 'login':
      loginClick()
      break
    default:
      break
  }
}
// 拼图验证成功函数
async function onSuccess() {
  isShow.value = false
  const res=await loginApi(form.value)
  setKey('userinfoResult',res.result)
  Object.keys(userStore.userInfo).forEach(item=>{
    userStore.userInfo[item]=res.result[item]
  })
  
  userStore.token=res.token
  setKey('token',res.token)
  router.push('/dataCenter')
}

function changeFormSaveVal(e) {
  formSaveVal.value = e
}
// 登录按钮点击处理
function loginClick() {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    isShow.value = true
    if (formSaveVal.value) {
      setKey('userinfo', { account: form.value.account, password: form.value.password })
    } else {
      removeKey('userinfo')
    }
  })
}

// 注册按钮点击处理
function registerClick() {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    const res =await registerApi({account:registerForm.value.account,password:registerForm.value.password})
      showMessage(res.message,res.status!==1?'success':'error')
  })
}
</script>

<template>
  <div class="login-wrapper">
    <div class="form-wrapper">
      <div class="form-title">
        <div class="title-top">欢迎</div>
        <div class="title-bottom">---Welcomee---</div>
      </div>
      <div class="form-contennt">
        <el-tabs v-model="activeName" @tab-click="handleTabClick" stretch>
          <!-- 登录  -->
          <el-tab-pane label="登录" name="login">
            <el-form
              :model="form"
              label-width="auto"
              :rules="rules"
              ref="loginFormRef"
              hide-required-asterisk
            >
              <el-form-item prop="account">
                <el-icon :size="25" style="margin-right: 20px"><UserFilled /></el-icon>
                <el-input
                  class="icon-input"
                  v-model.trim="form.account"
                  placeholder="请输入账号"
                />
              </el-form-item>
              <el-form-item prop="password">
                <el-icon :size="25" style="margin-right: 20px"><Lock /></el-icon>
                <el-input v-model.trim="form.password" placeholder="请输入密码" type="password" />
              </el-form-item>
            </el-form>
            <div class="form-config">
              <div class="form-save">
                <el-checkbox
                  label="记住密码"
                  :value="formSaveVal"
                  :checked="formSaveVal"
                  @change="changeFormSaveVal"
                />
              </div>
              <div class="form-reset" @click="resetForm" style="cursor: pointer">重置密码</div>
            </div>
            <div class="form-footer">
              <el-button type="primary" @click="onLogin('login')" size="large" class="login-btn"
                >登录</el-button
              >
            </div>
          </el-tab-pane>
          <!-- 注册 -->
          <el-tab-pane label="注册" name="register">
            <el-form
              :model="registerForm"
              label-position="left"
              label-suffix="："
              label-width="auto"
              :rules="registerRules"
              hide-required-asterisk
              ref="registerFormRef"
            >
              <el-form-item prop="account" label="账号">
                <el-input
                  class="icon-input"
                  v-model.trim="registerForm.account"
                  placeholder="请输入账号"
                />
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input
                  v-model.trim="registerForm.password"
                  placeholder="请输入密码"
                  type="password"
                />
              </el-form-item>
              <el-form-item prop="repassword" label="确认密码">
                <el-input
                  v-model.trim="registerForm.repassword"
                  placeholder="请再次输入密码"
                  type="password"
                />
              </el-form-item>
            </el-form>
            <div class="form-footer">
              <el-button type="primary" @click="onLogin('register')" size="large" class="login-btn"
                >注册</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <Vcode :show="isShow" @success="onSuccess" :sliderSize="40" />
  </div>
</template>

<style lang="scss" scoped>
.login-wrapper {
  position: relative;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background: url('@/assets/image/login/login-bg.png') no-repeat center/100% 100%;
  .form-wrapper {
    position: absolute;
    right: 8%;
    top: 50%;
    width: 440px;
    transform: translateY(-60%);
    padding: 20px 25px;
    background-color: white;
    border-radius: 20px;
    overflow: hidden;
    border: 2px solid #797979;
    .form-title {
      margin: 20px 0 5px 0;
      font-size: 28px;
      font-family: 'PMZDR';
      letter-spacing: 10px;
      color: rgb(10, 149, 241);
      margin-top: 15px;
      animation: formTitleColor 2.5s infinite alternate;
      text-align: center;
    }
    .form-contennt {
      padding: 20px 0;
      padding-bottom: 10px;
    }
    .form-config {
      width: 100%;
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      margin-top: -20px;
      margin-bottom: 20px;
    }
    :deep() {
      .login-btn {
        height: 30px;
        font-size: 18px;
        padding: 15px 80px;
        &:active {
          transform: translateY(2px);
        }
      }
      .el-tabs__content {
        margin-top: 25px;
      }
    }
  }
}
:deep(.el-input) {
  width: 280px;
}
:deep(.el-input__wrapper) {
  height: 42px;
  border-radius: 20px;
  padding: 2px 20px;
  font-size: 15px;
}
:deep(.el-form-item) {
  margin-bottom: 25px;
}
:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}

:deep(.el-input__inner) {
  &::placeholder {
    text-align: center;
  }
}
:deep(.el-form-item__error) {
  left: 70px;
}
</style>
